package al.xc.task;

import al.xc.common.task.ITaskRunnable;
import al.xc.common.task.TaskThread;

import java.util.HashSet;
import java.util.Set;

/**
 * 任务管理类
 */
public class LogicTaskManager extends TaskThread {


    /**
     * 唯一性判断
     */
    Set<ILogicTask.TaskKey> unique_set_ = new HashSet<>();

    /**
     * 添加任务
     * @param type
     * @param index
     * @param runnable
     */
    public boolean addTask(Integer type, String index, ITaskRunnable runnable) {
        if (null == index) {
            return addTask(new LogicTask(new ILogicTask.TaskKey(type, index), runnable));
        } else {
            ILogicTask.TaskKey taskKey = new ILogicTask.TaskKey(type, index);
            synchronized (unique_set_) {
                if (unique_set_.contains(taskKey)) {
                    return false;
                }
                unique_set_.add(taskKey);
            }
            return addTask(new LogicTask(taskKey, runnable));
        }
    }

    /**
     * 初始化线程
     */
    public void initialize() {
        super.initialize(1, this.getClass().getName(), (runnable) -> {return runBefore(runnable);});
    }

    /**
     * 反初始化
     */
    public void unInitialize() {
        super.unInitialize();
    }

    /**
     * 执行之前调用
     *
     * @param runnable
     */
    protected boolean runBefore(ITaskRunnable runnable) {
        ILogicTask task = (ILogicTask)runnable;
        if (null == task) {
            return false;
        }
        ILogicTask.TaskKey key = task.getKey();
        if (null != key && null != key.getIndex()) {
            synchronized (unique_set_) {
                unique_set_.remove(key);
            }
        }
        return true;
    }
}
